package com.onpositive.notes.argumnets;

import java.util.Locale;

import com.onpositive.notes.impl.AbstractEntityWithClass;
import com.onpositive.notes.model.IArgumentModel;
import com.onpositive.notes.model.ITemplate;
import com.onpositive.notes.model.ITemplateArgument;
import com.onpositive.notes.model.ITemplateModel;
import com.onpositive.notes.services.BasicNoteRegistry;
import com.onpositive.notes.services.TemplateModelRegistry;

public abstract class AbstractTemplateArgument<T> extends AbstractEntityWithClass<T> implements ITemplateArgument<T> {
	
	private static final long serialVersionUID = -1512085034968074222L;

	public AbstractTemplateArgument(){}
	
	public AbstractTemplateArgument(
			T value,
			BasicArgumentModel<T, ? extends AbstractTemplateArgument<T>> model,			
			Class<T> clazz,
			boolean isRequired)
	{
		super(clazz);
		this.value = value ;
		this.modelId = model.getId() ;
		this.isRequired = isRequired ;
	}
	
	private T value ;
	private int modelId ;
	private boolean isRequired ;
	private int templateId ;
	private String templateModelId ;

	@Override
	public T getArgumentValue() {
		return value;
	}

	@Override
	@SuppressWarnings("unchecked")
	public void setValue(Object obj) {
		if( getSubjectClass().isInstance(obj) )
			this.value = (T) obj ;
	}
	

	public boolean isRequired() {
		return isRequired;
	}

	public void setRequired(boolean isRequired) {
		this.isRequired = isRequired;
	}

	@Override
	public BasicArgumentModel<T, ? extends ITemplateArgument<T>> getModel() {
		
		ITemplateModel<?> model = TemplateModelRegistry.getInstance().getModelById( getTemplateModelId() ) ;
		if( model == null )
			return null ;
		
		IArgumentModel<?,?> argModel = model.getArgumentModel(modelId);
		if( argModel == null )
			return null ;
		
		if( argModel.getSubjectClass() != getSubjectClass() )
			return null ;
				
		return (BasicArgumentModel<T, ? extends ITemplateArgument<T>>) argModel;
	}

	@Override
	public String getLabel() {
		BasicArgumentModel<T, ? extends ITemplateArgument<T>> model = getModel();
		if( model == null )
			return null ;
		
		return model.getLabel(this);
	}

	@Override
	public String getLabel(Locale locale) {
		BasicArgumentModel<T, ? extends ITemplateArgument<T>> model = getModel();
		if( model == null )
			return null ;
		
		return model.getLabel(this,locale);
	}
	
	public String toString(){
		return value != null ? value.toString() : "NULL" ;
	}
	

	@Override
	public ITemplate getTemplate() {		
		return BasicNoteRegistry.getInstance().getTemplate(templateId) ;
	}

	@Override
	public void setTemplateId(int templateId) {
		this.templateId = templateId ;		
	}

	public String getTemplateModelId() {
		return templateModelId;
	}

	public void setTemplateModelId(String templateModelId) {
		this.templateModelId = templateModelId ;
	}
}
